package com.example.demo.swj.uitl;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.security.Security;


/**
 * ----------------------------------------------
 * <p>
 * ----------------------------------------------
 *
 * @author baidh@neuqsoft.com
 * @create 2020/7/30 0020
 * ----------------------------------------------
 */
@Slf4j
public class SignUtil {

    static {
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        }
    }

    public static String rsa2Sign(String content, String privateKey, String charset) {
        byte[] data = content.getBytes(Charset.forName(charset));
        Sign signUtil = SecureUtil.sign(SignAlgorithm.SHA256withRSA, privateKey, null);
        byte[] signed = signUtil.sign(data);
        return Base64.encode(signed);
    }

    public static boolean rsa2SignValid(String content, String sign, String publicKey, String charset) {
        byte[] data = content.getBytes(Charset.forName(charset));
        Sign signUtil = SecureUtil.sign(SignAlgorithm.SHA256withRSA, null, publicKey);
        byte[] signed = Base64.decode(sign.getBytes());
        return signUtil.verify(data, signed);
    }

//    public static String smSign(String content, String privateKey, String charset) {
//        byte[] data = content.getBytes(Charset.forName(charset));
//        Sign signUtil = new Sign("SM3withSM2", privateKey, null);
//        byte[] signed = signUtil.sign(data);
//        return Base64.encode(signed);
//    }
//
//    public static boolean smSignValid(String content, String sign, String publicKey, String charset) {
//        byte[] data = content.getBytes(Charset.forName(charset));
//        Sign signUtil = new Sign("SM3withSM2", null, publicKey);
//        byte[] signed = Base64.decode(sign.getBytes());
//        return signUtil.verify(data, signed);
//    }


    @SneakyThrows
    public static String smSign(String appId, String content, String privateKey, String charset) {
        return SMUtil.sm2SignStr(SMUtil.sm2Sign(privateKey, appId, content));
    }

    @SneakyThrows
    public static boolean smSignValid(String appId, String content, String sign, String publicKey, String charset) {
        return SMUtil.sm2SignValid(publicKey, appId, content, SMUtil.sm2SignStr(sign));
    }


}
